#include "mysql_relationship.h"

#include "log.h"
#include "relationship-odb.hxx"

namespace chat {
bool RelationshipTable::insert(const std::string& user_id,
                               const std::string& peer_id) {
    try {
        Relationship relationship1(user_id, peer_id);
        Relationship relationship2(peer_id, user_id);

        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->persist(relationship1);
        db_->persist(relationship2);

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("新增好友关系[{}-{}]失败: {}", user_id, peer_id, e.what());

        return false;
    }

    return true;
}
bool RelationshipTable::remove(const std::string& user_id,
                               const std::string& peer_id) {
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        db_->erase_query<Relationship>(
            odb::query<Relationship>::user_id == user_id &&
            odb::query<Relationship>::peer_id == peer_id);
        db_->erase_query<Relationship>(
            odb::query<Relationship>::user_id == peer_id &&
            odb::query<Relationship>::peer_id == user_id);

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("删除好友关系[{}-{}]失败: {}", user_id, peer_id, e.what());

        return false;
    }

    return true;
}

bool RelationshipTable::exist(const std::string& user_id,
                              const std::string& peer_id) {
    bool ret = false;
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        odb::result<Relationship> r = db_->query<Relationship>(
            odb::query<Relationship>::user_id == user_id &&
            odb::query<Relationship>::peer_id == peer_id);

        ret = !r.empty();

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("根据user_id[{}]和peer_id[{}]获取关系失败: {}", user_id,
                  peer_id, e.what());

        return false;
    }

    return ret;
}
std::vector<std::string> RelationshipTable::friends(
    const std::string& user_id) {
    std::vector<std::string> friends;
    try {
        // 获取事务对象开启事务
        odb::transaction trans(db_->begin());

        odb::result<Relationship> r = db_->query<Relationship>(
            odb::query<Relationship>::user_id == user_id);

        for (auto& relationship : r) {
            friends.push_back(relationship.peer_id());
        }

        // 提交事务
        trans.commit();

    } catch (const std::exception& e) {
        LOG_ERROR("根据user_id[{}]获取好友列表失败: {}", user_id, e.what());

        return friends;
    }

    return friends;
}
}  // namespace chat